package com.reptile.science;

import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.Site;
import us.codecraft.webmagic.Spider;
import us.codecraft.webmagic.processor.PageProcessor;

/**
 * @author code4crafter@gmail.com <br>
 */
public class SinaBlogProcessor implements PageProcessor {

    public static final String URL_LIST = "http://www\\.javazhang\\.com";

    public static final String URL_POST = "https://www\\.javazhang\\.com/post/\\w";

    private Site site = Site
            .me()
            .setDomain("www.javazhang.com")
            .setSleepTime(3000)
            .setUserAgent(
                    "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.132 Safari/537.36");

    @Override
    public void process(Page page) {
        //列表页
        if (page.getUrl().regex(URL_LIST).match()) {
//            page.addTargetRequests(page.getHtml().xpath("//div[@class=\"articleList\"]").links().regex(URL_POST).all());
//            page.addTargetRequests(page.getHtml().links().regex(URL_LIST).all());
              page.addTargetRequests(page.getHtml().xpath("//div[@class=\"mdui-typo-headline mdui-m-b-3 index-list-title index-guo\"]").links().regex(URL_POST).all());
              page.addTargetRequests(page.getHtml().links().regex(URL_LIST).all());
              System.out.println(page.getHtml().xpath("//div[@class='mdui-col-md-8']//article[@class='mdui-p-a-5']//div[@class='post-title']").links().regex(URL_POST).all());
        //文章页
        } else {
//            page.putField("title", page.getHtml().xpath("//div[@class='articalTitle']/h2"));
//            page.putField("content", page.getHtml().xpath("//div[@id='articlebody']//div[@class='articalContent']"));
//            page.putField("date", page.getHtml().xpath("//div[@id='articlebody']//span[@class='time SG_txtc']").regex("\\((.*)\\)"));
            try {
                System.out.println("进了else");
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            page.putField("title",page.getHtml().xpath("//div[@class='post-title']//article[class='mdui-p-a-5']"));
            page.putField("content",page.getHtml().xpath("//article[@class='mdui-p-a-2']//div[@class='mdui-m-b-2']"));
        }
    }

    @Override
    public Site getSite() {
        return site;
    }

    public static void main(String[] args) {
        Spider.create(new SinaBlogProcessor()).addUrl("http://www.javazhang.com").run();
    }
}